import datetime
import json
from multiprocessing.pool import ThreadPool

import requests

from Spider.api import RawRequestAPI, TuShareAPI
from Spider.config import CONFIG, G
from Spider.tool import cal_run_time

G_MESSAGE_QUEUE = None

STACK_STATE_MAP = {
    -1: "异常",
    1: "持股",
    2: "买A卖H",
    3: "卖A买H"
}


def get_stacks():
    """
    1天刷新1次

    获取所有股票代码
    :return:
    """
    response = requests.get("{}/index/api/refresh_stack/".format(CONFIG.LOCAL_URL))
    stacks = json.loads(response.text)
    return stacks


def get_details(stack):
    """
    获取 买1卖1还有成交量

    港股为116.0 + 4位股票代号
    A股为 1. + 6位A股代码
    基金为0. + 基金代号


    :param code:
    :return:
    """
    s_20mean = stack["s_20mean"]
    name = stack["s_name"]
    acode = stack["s_acode"]
    result = {
        "acode": acode,
        "name": name,
        "flag": stack["s_flag_refresh"],
        "20mean": s_20mean
    }
    state_in_database = stack['s_flag']
    if stack["s_flag_refresh"] == 1:
        acode = stack["s_acode"]
        hcode = stack["s_hcode"]
        time, a_buy_1, a_sell_1, turnover = TuShareAPI.get_one_buy1_sell1_turnover(acode)

        # TODO 如果出现问题找其它API
        h_wap_eastmoney_code = "116.0" + hcode[:-3]
        time_str, h_buy_1, h_sell_1 = RawRequestAPI.get_buy_sell_1(h_wap_eastmoney_code)
        time = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M').time().strftime("%H:%M")

        # 发送信息逻辑
        as_hb = round(float(a_sell_1) / float(h_buy_1), 3)
        as_hb_dep = round((as_hb - s_20mean) / s_20mean * 100, 2)
        as_hb_dep_str = str(as_hb_dep) + '%'

        ab_hs = round(float(a_buy_1) / float(h_sell_1), 3)
        ab_hs_dep = round((ab_hs - s_20mean) / s_20mean * 100, 2)
        ab_hs_dep_str = str(ab_hs_dep) + '%'
        # 获取状态
        try:
            if as_hb_dep > 1 and ab_hs_dep > 1:
                state = 2  # 买A卖H
            elif as_hb_dep < -1 and ab_hs_dep < -1:
                state = 3  # 卖A买H
            else:
                state = 1  # 持股
            if state_in_database != state:
                requests.patch("{}/index/api/stack/{}/".format(CONFIG.LOCAL_URL, stack['s_id']),
                               data={"s_flag": state})
                G.MESSAGE_QUEUE_LOCK.acquire()
                G_MESSAGE_QUEUE.put(
                    "股票{}，A股编号{}，状态由{}变更为{}".format(name, acode,
                                                    STACK_STATE_MAP[state_in_database], STACK_STATE_MAP[state]))
                G.MESSAGE_QUEUE_LOCK.release()
        except:
            state = -1

        result.update({
            "abuy1": a_buy_1,
            "asell1": a_sell_1,
            "hbuy1": h_buy_1,
            "hsell1": h_sell_1,
            "turnover": turnover,
            "time": time,
            "AS:HB": as_hb,
            "AS:HB_dep": as_hb_dep_str,
            "AB:HS": ab_hs,
            "AB:HS_dep": ab_hs_dep_str,
            "state": STACK_STATE_MAP[state]
        })
    return result


@cal_run_time(cal_func_place="股票")
def refresh_data():
    task_pool = ThreadPool(120)
    stacks = get_stacks()
    result = task_pool.map(get_details, stacks)
    return result


def run(MESSAGE_QUEUE):
    global G_MESSAGE_QUEUE
    G_MESSAGE_QUEUE = MESSAGE_QUEUE
    while True:
        result = refresh_data()
        # print("获取股票数据：", json.dumps(result, ensure_ascii=False))
        try:
            requests.post("{}/index/post/stack/".format(CONFIG.LOCAL_URL), data={'data': json.dumps(result)})
        except Exception as e:
            print(e)
    # task_pool.close()
    # task_pool.join()
